package com.weme.common.util

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import com.weme.google.GoogleLoginHelper
import java.lang.ref.WeakReference
import java.util.*

object UtilsApp {

    @SuppressLint("StaticFieldLeak")
    private var sApplication: Application? = null
    private var context: WeakReference<Context>? = null

    private val sActivityList = LinkedList<WeakReference<FragmentActivity>>()

    fun init(app: Application) {
        sApplication = app
        app.registerActivityLifecycleCallbacks(mCallbacks)
        context = WeakReference(app.applicationContext)
    }

    fun getApp(): Application {
        return sApplication ?: throw NullPointerException("You should initialize UtilsApp first.")
    }

    fun getContext(): Context {
        return context?.get() ?: throw NullPointerException("You should initialize UtilsApp first.")
    }

    fun getActivityList() : List<WeakReference<FragmentActivity>> {
        return sActivityList.reversed()
    }

    fun getVersionName(): String? {
        return try {
            val packageManager: PackageManager = getApp().packageManager
            val packInfo: PackageInfo = packageManager.getPackageInfo(getApp().packageName, 0)
            packInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            null
        }
    }

    fun getSystemModel(): String {
        return Build.MODEL
    }

    fun isTopActivity(activity: FragmentActivity): Boolean {
        return activity == getTopActivity()
    }

    fun getTopActivity(): FragmentActivity {
        val lastActivity = sActivityList.lastOrNull()?.get()
        return lastActivity!!
    }

    fun back() {
        getTopActivity().finish()
    }
    fun finishAll(){
        sActivityList.forEach {
            it.get()?.finish()
        }
    }

    private val mCallbacks: Application.ActivityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
            if(activity is FragmentActivity){
                sActivityList.add(WeakReference(activity))
            }

        }

        override fun onActivityStarted(activity: Activity) {
         //   Log.e("socket","启动app")
        }

        override fun onActivityResumed(activity: Activity) {}

        override fun onActivityPaused(activity: Activity) {}

        override fun onActivityStopped(activity: Activity) {
        //    Log.e("socket","退出到后台")
        }

        override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}

        override fun onActivityDestroyed(activity: Activity) {
            val iterator = sActivityList.iterator()
            while (iterator.hasNext()) {
                val activityRef = iterator.next()
                val currentActivity = activityRef.get()
                if (currentActivity == null || currentActivity == activity) {
                    iterator.remove()
                }
            }
        }
    }


    fun outLogin(){
        finishAll()
        UserMKHelper.clearAll()
        AgoraClient.signOut()
        GoogleLoginHelper.signOut(getTopActivity())
    }
}
